﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AspNetCore.Host.Hosting;
using AspNetCore.Host.Mvc;
using AspNetCore.Host.Routing;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class IMvcEndpointRouteBuilderExtensions
    {
        public static void MapControllers(this WebApplication app)
        {
           
            var endpoints = app.ServerFeatures.Get<EndpointDataSource>();
            if (endpoints == null)
            {
                return;
            }
            var assembly = Assembly.GetExecutingAssembly();
            var controllers = assembly.GetTypes().Where(a => a.IsSubclassOf(typeof(ControllerBase)));
            foreach (var item in controllers)
            {
                var methods = item.GetMethods(BindingFlags.Public | BindingFlags.Instance);
                foreach (var method in methods)
                {
                    var httpMethod = method.GetCustomAttributes()
                        .Where(a => a is HttpMethodAttribute).FirstOrDefault();
                    if (httpMethod==null)
                    {
                        continue;
                    }
                    RequestDelegate handler = context =>
                    {
                        var controller = ActivatorUtilities.CreateInstance(context.RequestServices, item);
                        if (controller is ControllerBase controllerBase)
                        {
                            controllerBase.HttpContext = context;
                        }
                        //modelBinder
                        method.Invoke(controller, new object[0]);
                        return Task.CompletedTask;
                    };
                    var endpint = new Endpoint(handler);
                    endpint.Metadata.Add(httpMethod);
                    endpoints.SetEndpoint(endpint);
                }
            }

            app.UseRouting();
        }
    }
}
